package com.admin.intercepter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.admin.base.SysConstant.SESSION_USER;


/**
 * 登录验证拦截器
 *
 * @time 2019.08.9
 */
@Component
public class LoginIntercepter implements HandlerInterceptor {
    private static final Logger LOGGER = LogManager.getLogger(LoginIntercepter.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if(requestURI.indexOf("/login")<=0){
            //说明处在编辑的页面
            Object obj = request.getSession().getAttribute(SESSION_USER);
            if(obj == null){
                LOGGER.warn("用户未登录,无法访问");
                String xhrHeader = request.getHeader("X-Requested-With");

                //当请求是传统方式时
                if( !"XMLHttpRequest".equalsIgnoreCase(xhrHeader)) {
                    //没有登陆，转向登陆界面
                    request.getRequestDispatcher("/").forward(request,response);
                    return false;
                }
                //当请求是ajax方式时
                if(xhrHeader != null && "XMLHttpRequest".equalsIgnoreCase(xhrHeader)) {
                    LOGGER.debug("异步请求URl:{}",requestURI);
                    response.sendError(HttpStatus.UNAUTHORIZED.value());
                    return false;
                }
            }
            LOGGER.debug("当前登录用户:{}", obj);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
